<template>
  <view class="detail-container">
    <!-- 作品展示区域 -->
    <view class="artwork-display">
      <!-- 图片对比区域 -->
      <swiper class="image-swiper" :indicator-dots="true" indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#FF69B4">
        <swiper-item>
          <view class="swiper-item">
            <image :src="(artwork.resultImage) || '/static/images/default-image.png'" mode="aspectFit" @click="previewImage(artwork.resultImage)"></image>
            <text class="image-label">AI风格</text>
          </view>
        </swiper-item>
        <swiper-item>
          <view class="swiper-item">
            <image :src="(artwork.originalImage) || '/static/images/default-image.png'" mode="aspectFit" @click="previewImage(artwork.originalImage)"></image>
            <text class="image-label">原图</text>
          </view>
        </swiper-item>
      </swiper>
      
      <!-- 创建时间 -->
      <view class="create-time">
        创建于 {{ formatDateTimeStr(artwork.createTime) }}
      </view>
    </view>
    
    <!-- 作品信息区域 -->
    <view class="artwork-info">
      <!-- 作者信息 -->
      <view class="author-info" @click="navigateToProfile(artwork.user && artwork.user.id)">
        <image class="author-avatar" :src="(artwork.user && artwork.user.avatar) || '/static/images/default-avatar.png'" mode="aspectFill"></image>
        <view class="author-detail">
          <text class="author-name">{{ (artwork.user && artwork.user.nickname) || (artwork.user && artwork.user.username) || '未知用户' }}</text>
          <!-- <text class="publish-time">{{ formatRelativeTimeStr(artwork.createTime) }}</text> -->
        </view>
        <view class="follow-btn" v-if="!isCurrentUser && artwork.user && artwork.user.id">
          <follow-button :user-id="artwork.user.id"></follow-button>
        </view>
      </view>
      
      <!-- 作品标题 -->
      <view class="info-section">
        <view class="section-title">作品标题</view>
        <view class="artwork-title">{{ artwork.title }}</view>
      </view>
      
      <!-- 风格标签 -->
      <view class="info-section">
        <view class="section-title">使用风格</view>
        <view class="style-tags">
          <view class="tag-item" v-for="(tag, index) in artwork.tags" :key="index">
            {{ tag }}
          </view>
        </view>
      </view>
      
      <!-- AI描述 -->
      <view class="info-section">
        <view class="section-title">AI描述</view>
        <view class="ai-description">
          {{ artwork.description }}
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button class="action-btn save-btn" @click="saveToAlbum">
          <text class="btn-icon">💾</text>
          <text class="btn-text">保存到相册</text>
        </button>
        <button class="action-btn share-btn" @click="shareArtwork">
          <text class="btn-icon">🔗</text>
          <text class="btn-text">分享作品</text>
        </button>
      </view>
    </view>
    
    <!-- 互动区域 -->
    <view class="interaction-area">
      <view class="like-btn" @click="likeArtwork">
        <text class="iconfont icon-like" :class="{ active: artwork.isLiked }">❤️</text>
        <text class="count">{{ artwork.likeCount }}</text>
      </view>
      <view class="comment-btn">
        <text class="iconfont icon-comment">💬</text>
        <text class="count">{{ artwork.commentCount }}</text>
      </view>
    </view>
    
    <!-- 评论区域 -->
    <view class="comments-area">
      <view class="comments-header">
        <text class="comments-title">评论 ({{ comments.length }})</text>
        <text class="sort-btn">最新</text>
      </view>
      
      <!-- 评论列表 -->
      <view class="comments-list">
        <view class="comment-item" v-for="(comment, index) in comments" :key="index">
          <view class="comment-header">
            <view class="comment-user" @click="navigateToProfile(comment.userId)">
              <image class="user-avatar" :src="comment.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
              <text class="user-name">{{ comment.username }}</text>
            </view>
            <text class="comment-time">{{ formatRelativeTimeStr(comment.createTime) }}</text>
          </view>
          <view class="comment-content">
            {{ comment.content }}
          </view>
        </view>
        <view class="no-comment" v-if="comments.length === 0">
          <text>暂无评论，快来发表第一条评论吧</text>
        </view>
      </view>
      
      <!-- 评论输入框 -->
      <view class="comment-input">
        <input 
          type="text" 
          v-model="commentText" 
          placeholder="写下你的评论..." 
          confirm-type="send"
          @confirm="submitComment"
        />
        <button class="send-btn" @click="submitComment">发送</button>
      </view>
    </view>
    
    <!-- 相似作品推荐 -->
    <view class="similar-works">
      <view class="similar-title">相似作品推荐</view>
      <scroll-view scroll-x class="similar-list">
        <view 
          class="similar-item" 
          v-for="(item, index) in similarWorks" 
          :key="index"
          @click="goToDetail(item.id)"
        >
          <image :src="item.resultUrl" mode="aspectFill"></image>
          <view class="similar-tags">
            <text class="similar-tag" v-for="(tag, tagIndex) in ((item.tags && item.tags.length > 0) ? item.tags.slice(0, 2) : [])" :key="tagIndex">
              {{ tag }}
            </text>
            <!-- 如果没有标签，显示一个默认标签 -->
            <text class="similar-tag" v-if="!item.tags || item.tags.length === 0">
              相似作品
            </text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import * as commonUtils from '@/utils/common.js';
import { feedApi, userApi } from '@/utils/api.js';
import FollowButton from '@/components/user/FollowButton.vue';

export default {
  components: {
    FollowButton
  },
  data() {
    return {
      // 作品ID
      artworkId: null,
      // 评论文本
      commentText: '',
      // 加载状态
      loading: {
        artwork: false,
        comments: false,
        similarWorks: false
      },
      
      // 作品信息
      artwork: {
        id: null,
        userId: null,
        username: '',
        userAvatar: '',
        originalUrl: '',
        resultUrl: '',
        title: '',
        tags: [],
        description: '',
        createTime: '',
        likeCount: 0,
        commentCount: 0,
        isLiked: false
      },
      
      // 评论列表
      comments: [],
      
      // 相似作品推荐
      similarWorks: [],
      
      // 是否为当前用户
      isCurrentUser: false
    }
  },
  
  onLoad(options) {
    console.log('作品详情页面接收到的参数：', options);
    if (options.id) {
      this.artworkId = parseInt(options.id);
      this.loadArtworkDetail();
      this.loadComments();
      this.loadSimilarWorks();
    }
  },
  
  methods: {
    // 格式化日期时间
    formatDateTimeStr(time) {
      return commonUtils.formatDateTime(time);
    },
    
    // 格式化相对时间
    formatRelativeTimeStr(time) {
      return commonUtils.formatRelativeTime(time);
    },
    
    // 加载作品详情
    async loadArtworkDetail() {
      if (this.loading.artwork) return;
      
      try {
        this.loading.artwork = true;
        const res = await feedApi.getFeedDetail(this.artworkId);
        
        if (res.code === 200 && res.data) {
          this.artwork = res.data;
          // 检查是否为当前用户
          const currentUser = await userApi.getUserInfo();
          if (currentUser.code === 200 && currentUser.data) {
            this.isCurrentUser = currentUser.data.id === this.artwork.user?.id;
          }
        } else {
          uni.showToast({
            title: res.message || '获取作品详情失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取作品详情失败:', error);
        uni.showToast({
          title: '获取作品详情失败，请检查网络',
          icon: 'none'
        });
      } finally {
        this.loading.artwork = false;
      }
    },
    
    // 加载评论列表
    loadComments() {
      if (!this.artworkId) return;
      
      this.loading.comments = true;
      
      feedApi.getComments(this.artworkId)
        .then(res => {
          if (res.code === 200 && res.data) {
            this.comments = res.data.list.map(item => ({
              id: item.id,
              artworkId: item.workId,
              userId: item.userId,
              username: item.userName || item.nickname || '用户',
              avatar: item.avatar || '/static/images/default-avatar.png',
              content: item.content,
              createTime: item.createTime
            }));
            
            // 更新评论数
            if (this.artwork && this.comments.length > 0) {
              this.artwork.commentCount = this.comments.length;
            }
          } else {
            uni.showToast({
              title: res.message || '获取评论失败',
              icon: 'none'
            });
          }
        })
        .catch(err => {
          console.error('加载评论失败:', err);
          uni.showToast({
            title: '加载评论失败，请检查网络',
            icon: 'none'
          });
        })
        .finally(() => {
          this.loading.comments = false;
        });
    },
    
    // 加载相似作品推荐
    loadSimilarWorks() {
      if (!this.artworkId) return;
      
      this.loading.similarWorks = true;
      
      feedApi.getSimilarWorks(this.artworkId)
        .then(res => {
          if (res.code === 200 && res.data) {
            this.similarWorks = res.data.map(item => ({
              id: item.id,
              resultUrl: item.resultUrl || item.resultImage,
              tags: item.tags || []
            }));
          } else {
            uni.showToast({
              title: res.message || '获取相似作品失败',
              icon: 'none'
            });
          }
        })
        .catch(err => {
          console.error('加载相似作品失败:', err);
          uni.showToast({
            title: '加载相似作品失败，请检查网络',
            icon: 'none'
          });
        })
        .finally(() => {
          this.loading.similarWorks = false;
        });
    },
    
    // 预览图片
    previewImage(url) {
      uni.previewImage({
        urls: [url],
        current: url
      });
    },
    
    // 保存到相册
    saveToAlbum() {
      uni.showLoading({
        title: '保存中...'
      });
      
      // 下载图片到本地
      uni.downloadFile({
        url: this.artwork.resultUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            // 保存图片到相册
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.hideLoading();
                uni.showToast({
                  title: '已保存到相册',
                  icon: 'success'
                });
              },
              fail: (err) => {
                uni.hideLoading();
                console.error('保存失败:', err);
                uni.showToast({
                  title: '保存失败，请检查权限设置',
                  icon: 'none'
                });
              }
            });
          } else {
            uni.hideLoading();
            uni.showToast({
              title: '下载图片失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({
            title: '下载图片失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 分享作品
    shareArtwork() {
      uni.showLoading({
        title: '生成分享海报...'
      });
      
      feedApi.generateSharePoster({ artworkId: this.artwork.id })
        .then(res => {
          uni.hideLoading();
          
          if (res.code === 200 && res.data) {
            // 预览海报
            uni.previewImage({
              urls: [res.data.posterUrl || res.data]
            });
          } else {
            uni.showToast({
              title: res.message || '生成海报失败',
              icon: 'none'
            });
          }
        })
        .catch(err => {
          console.error('生成分享海报失败:', err);
          uni.hideLoading();
          
          uni.showToast({
            title: '生成海报失败，请稍后再试',
            icon: 'none'
          });
        });
    },
    
    // 点赞作品
    likeArtwork() {
      if (!this.artwork.id) return;
      
      // 乐观更新UI
      const originalLikeStatus = this.artwork.isLiked;
      const originalLikeCount = this.artwork.likeCount;
      
      // 先更新UI状态
      if (this.artwork.isLiked) {
        this.artwork.likeCount--;
      } else {
        this.artwork.likeCount++;
      }
      this.artwork.isLiked = !this.artwork.isLiked;
      
      // 调用API
      feedApi.interact({
        targetId: this.artwork.id,
        type: 'like'
      }).catch(err => {
        console.error('点赞失败:', err);
        // 恢复原状态
        this.artwork.isLiked = originalLikeStatus;
        this.artwork.likeCount = originalLikeCount;
        
        uni.showToast({
          title: err.message,
          icon: 'none'
        });
      });
    },
    
    // 提交评论
    submitComment() {
      if (!this.commentText.trim()) {
        uni.showToast({
          title: '评论内容不能为空',
          icon: 'none'
        });
        return;
      }
      
      if (!this.artwork.id) {
        uni.showToast({
          title: '作品信息加载中，请稍后再试',
          icon: 'none'
        });
        return;
      }
      
      // 创建临时评论对象（乐观UI更新）
      const tempComment = {
        id: Date.now(), // 临时ID
        artworkId: this.artwork.id,
        userId: 1,
        username: '我',
        avatar: '/static/images/default-avatar.png',
        content: this.commentText,
        createTime: new Date().toISOString()
      };
      
      // 先添加到列表
      this.comments.unshift(tempComment);
      this.artwork.commentCount++;
      
      // 清空输入框
      const commentText = this.commentText;
      this.commentText = '';
      
      // 调用API
      feedApi.interact({
        artworkId: this.artwork.id,
        type: 'comment',
        content: commentText
      })
        .then(res => {
          if (res.code === 200 && res.data) {
            // 用真实评论替换临时评论
            const realComment = {
              id: res.data.id,
              artworkId: this.artwork.id,
              userId: res.data.userId,
              username: res.data.userName || res.data.nickname || '我',
              avatar: res.data.avatar || tempComment.avatar,
              content: res.data.content,
              createTime: res.data.createTime
            };
            
            // 找到临时评论的索引并替换
            const index = this.comments.findIndex(c => c.id === tempComment.id);
            if (index !== -1) {
              this.comments.splice(index, 1, realComment);
            }
            
            uni.showToast({
              title: '评论成功',
              icon: 'success'
            });
          }
        })
        .catch(err => {
          console.error('评论失败:', err);
          
          // 从列表中移除临时评论
          const index = this.comments.findIndex(c => c.id === tempComment.id);
          if (index !== -1) {
            this.comments.splice(index, 1);
          }
          
          // 恢复评论数
          this.artwork.commentCount--;
          
          // 恢复评论文本
          this.commentText = commentText;
          
          uni.showToast({
            title: '评论失败，请稍后重试',
            icon: 'none'
          });
        });
    },
    
    // 跳转到其他作品详情
    goToDetail(id) {
      // 如果是当前作品，不跳转
      if (id === this.artworkId) return;
      
      uni.navigateTo({
        url: `/pages/detail/detail?id=${id}`
      });
    },
    
    // 跳转到用户主页
    navigateToProfile(userId) {
      if (!userId) {
        console.warn('用户ID不存在，无法跳转到个人主页');
        return;
      }
      
      console.log('跳转到用户主页：', userId);
      
      uni.navigateTo({
        url: `/pages/user/profile?id=${userId}`
      });
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/mixins.scss';

.detail-container {
  padding-bottom: 100rpx;
}

/* 作品展示区域 */
.artwork-display {
  position: relative;
}

.image-swiper {
  height: 800rpx;
  background-color: #f8f8f8;
}

.swiper-item {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  position: relative;
}

.swiper-item image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.image-label {
  position: absolute;
  bottom: 30rpx;
  left: 30rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.create-time {
  padding: 20rpx 30rpx;
  font-size: 24rpx;
  color: #999;
  text-align: right;
}

/* 作品信息区域 */
.artwork-info {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.author-info {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  
  .author-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    margin-right: 20rpx;
  }
  
  .author-detail {
    flex: 1;
    
    .author-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 4rpx;
    }
    
    .publish-time {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .follow-btn {
    margin-left: 20rpx;
  }
}

.info-section {
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
}

.style-tags {
  display: flex;
  flex-wrap: wrap;
}

.tag-item {
  font-size: 26rpx;
  color: #FF69B4;
  background-color: rgba(255, 105, 180, 0.1);
  padding: 8rpx 20rpx;
  border-radius: 30rpx;
  margin-right: 20rpx;
  margin-bottom: 15rpx;
}

.ai-description {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

.artwork-title {
  font-size: 36rpx;
  color: #333;
  margin: 10rpx 0;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
}

.action-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
  margin: 0 15rpx;
  border-radius: 12rpx;
}

.save-btn {
  background-color: #f8f8f8;
  color: #333;
}

.share-btn {
  background-color: #FF69B4;
  color: #fff;
}

.btn-icon {
  font-size: 40rpx;
  margin-bottom: 10rpx;
}

.btn-text {
  font-size: 28rpx;
}

/* 互动区域 */
.interaction-area {
  display: flex;
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.like-btn, .comment-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
}

.iconfont {
  margin-right: 10rpx;
  font-size: 36rpx;
}

.iconfont.active {
  color: #FF69B4;
}

.count {
  font-size: 28rpx;
}

/* 评论区域 */
.comments-area {
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.comments-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.sort-btn {
  font-size: 26rpx;
  color: #999;
}

.comments-list {
  margin-bottom: 30rpx;
}

.comment-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.comment-user {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  margin-right: 16rpx;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
}

.comment-time {
  font-size: 24rpx;
  color: #999;
}

.comment-content {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

.no-comment {
  padding: 40rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

.comment-input {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
}

.comment-input input {
  flex: 1;
  height: 70rpx;
  background-color: #f5f5f5;
  border-radius: 35rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
}

.send-btn {
  margin-left: 20rpx;
  background-color: #FF69B4;
  color: #fff;
  font-size: 28rpx;
  padding: 0 30rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
}

/* 相似作品推荐 */
.similar-works {
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.similar-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.similar-list {
  white-space: nowrap;
}

.similar-item {
  display: inline-block;
  width: 250rpx;
  margin-right: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
}

.similar-item image {
  width: 100%;
  height: 330rpx;
  border-radius: 12rpx;
}

.similar-tags {
  position: absolute;
  bottom: 10rpx;
  left: 10rpx;
  display: flex;
}

.similar-tag {
  font-size: 22rpx;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  margin-right: 10rpx;
}
</style>
